package com.infore.airsupervise.ui.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.DispatchAqiExpendAdapter;
import com.infore.airsupervise.adapter.DispatchSynthesisExpendAdapter;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.DispatchAqiE;
import com.infore.airsupervise.bean.DispatchAqiExpandE;
import com.infore.airsupervise.bean.DispatchSynthesisE;
import com.infore.airsupervise.bean.DispatchSynthesisExpandE;
import com.infore.airsupervise.bean.DispatchWeatherE;
import com.infore.airsupervise.biz.DispatchBiz;
import com.infore.airsupervise.biz.impl.DispatchBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.activity.DispatchActivity;
import com.infore.airsupervise.ui.widget.EmptyView;
import com.infore.airsupervise.ui.widget.ItemDecoration1px;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;

/**
 * 实时调度 - 综合指数
 */
public class DispatchSynthesisFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, DispatchActivity.OnDataTypeChangeListener {

    @BindView(R.id.recycler_view_dispatch)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeLayout;
    Unbinder unbinder;
    private EmptyView emptyView; // 无数据时填充view

    private DispatchSynthesisExpendAdapter expendAdapter;
    private List<MultiItemEntity> itemEntities = new ArrayList<>(); // 数据源

    private DispatchBiz dispatchBiz;
    private int page = 0;
    private int dataType = 0;


    public DispatchSynthesisFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dispatch, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        dispatchBiz = new DispatchBizImpl();
        return view;
    }

    private void initView() {
        // 设置swipeLayout
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(52,152,219), Color.rgb(231,76,60), Color.rgb(46,204,113));
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        });

        // 适配设置
        expendAdapter = new DispatchSynthesisExpendAdapter(itemEntities);
        expendAdapter.setOnLoadMoreListener(this);
        expendAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);

        // 列表设置
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new ItemDecoration1px(getContext(), ItemDecoration1px.VERTICAL_LIST));
        recyclerView.setAdapter(expendAdapter);

        // 设置emptyView
        emptyView = new EmptyView(getContext());
        emptyView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                swipeLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }

    /**
     * 通用成功处理
     */
    public void commonSuccessHandle(boolean isRefresh, int pageSize) {

        if (isRefresh) {
            // 结束刷新、使加载可用
            swipeLayout.setRefreshing(false);
            expendAdapter.setEnableLoadMore(true);
            // 无数据时显示
            if (pageSize == 0) {
                emptyView.setShowInfo(R.drawable.status_search_null, MsgConst.EMPTY_DATA);
                expendAdapter.setEmptyView(emptyView);
            }
            // 清空数据源
            itemEntities.clear();

        } else {
            if(pageSize>=10) {
                expendAdapter.loadMoreComplete();
            }
            // 使刷新可用
            swipeLayout.setEnabled(true);
        }
        //只要size小于10条
        if(pageSize < 10){
            expendAdapter.loadMoreEnd();
        }

        // page加1
        page += 1;
    }

    /**
     * 通用失败处理
     */
    public void commonFailedHandle(boolean isRefresh, int errorCode, String title, String desc) {

        if (isRefresh) {

            int imgRes = R.drawable.status_connect_failed;
            switch (errorCode) {
                case StatusConst.CODE_CONNECT_FAIL:
                    imgRes = R.drawable.status_connect_failed;
                    break;

                case StatusConst.CODE_CONNECT_TIMEOUT:
                    imgRes = R.drawable.status_timeout;
                    break;

                case StatusConst.CODE_SERVER_EXCEPTION:
                    imgRes = R.drawable.status_server_fix;
                    break;

                case StatusConst.CODE_OPERATION_FAIL:
                    imgRes = R.drawable.status_connect_failed;
                    break;
            }

            emptyView.setShowInfo(imgRes, title);
            expendAdapter.setEmptyView(emptyView);

            // toast提示
            ToastUtil.showLong(getContext(), desc);
            // 结束刷新
            swipeLayout.setRefreshing(false);

        } else {
            // 结束加载
            expendAdapter.loadMoreFail();
        }
    }

    /**
     * 获取网络数据
     * @param isRefresh
     */
    private void getDispatchAqiDatas(final boolean isRefresh) {
        Call<BaseResponse> call = dispatchBiz.getDispatchSynthesisList(page, dataType, new OnServerResponseListener<List<DispatchSynthesisE>>() {
            @Override
            public void onSucceed(List<DispatchSynthesisE> result, String desc) {

                commonSuccessHandle(isRefresh, result.size());

                if (result == null) {
                    return;
                }

                // 构建扩展列表需要的数据
                for (DispatchSynthesisE e : result) {
                    List<DispatchSynthesisE.SynthesisBean> dataList = e.getDataList();
                    DispatchSynthesisExpandE expandE = new DispatchSynthesisExpandE();
                    expandE.staName = e.getStationName();

                    if (dataList != null && dataList.size() > 0) {
                        expandE.nearData = dataList.get(dataList.size()-1);
                    } else {
                        expandE.nearData = new DispatchSynthesisE.SynthesisBean();
                    }
                    expandE.addSubItem(new DispatchSynthesisExpandE.FactorTrendE(dataList));
                    itemEntities.add(expandE);
                }

                // 刷新适配器
                expendAdapter.notifyDataSetChanged();
                expendAdapter.dataType = dataType;
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                commonFailedHandle(isRefresh, errorCode, title, desc);
            }
        });
        requests.add(call);
    }

    /**
     * 数据类型切换
     * @param dataType 0：分钟数据，1：小时数据，2：日数据
     */
    @Override
    public void onDataTypeChange(int dataType) {
        if (dataType == this.dataType) {
            return;
        }
        this.dataType = dataType;
        // 刷新
        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        // 使加载不可用
        expendAdapter.setEnableLoadMore(false);
        // page置0
        page = 0;
        // 获取数据
        getDispatchAqiDatas(true);
    }

    /**
     * 加载
     */
    @Override
    public void onLoadMoreRequested() {
        // 使刷新不可用
        swipeLayout.setEnabled(false);
        // 获取数据
        getDispatchAqiDatas(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
